#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
import time
import math
from aliyunsdkcore.client import AcsClient
from aliyunsdkcdn.request.v20141111 import DescribeDomainsUsageByDayRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models


def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        try:
            get_cdn_traffic(account)
        except Exception as e:
            pass

def get_cdn_traffic(account):
    client = AcsClient(account.access_id,account.access_secret,'cn-hangzhou')
    request = DescribeDomainsUsageByDayRequest.DescribeDomainsUsageByDayRequest()
    request.set_accept_format('json')
    current_time=time.time()
    before_time=current_time-24*60*60*1  #获取昨天的数据
    request.add_query_param('StartTime', time.strftime("%Y-%m-%d",time.gmtime(before_time)))
    request.add_query_param('EndTime', time.strftime("%Y-%m-%d",time.gmtime(before_time)))
    response = client.do_action_with_exception(request).decode('utf-8')
    response=json.loads(response)
    result_list=response['UsageByDays']['UsageByDay']
    for result in result_list:
        date_time=result['TimeStamp']
        timestamps=int(time.mktime(time.strptime(date_time,'%Y-%m-%d')))
        maxbps=result['MaxBps']
        if 'E' in maxbps:
            maxbps=str(int(float(maxbps.split("E")[0])*math.pow(10,int(maxbps.split("E")[1]))))
        else:
            maxbps=str(int(eval(maxbps)))
        totaltraffic=int(result['TotalTraffic'])
        cdnobj=models.CDNData(date_time=date_time,timestamps=timestamps,maxbps=maxbps,totaltraffic=totaltraffic,account=account)
        cdnobj.save()




if __name__=='__main__':
    main()
